package jp.co.sharp.android.parents.kidsguard.activity.setting;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.JsonReader;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.android.bluetooth.parentble.ParentBleTransfer;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.common.DealWithWaitingDlg;
import jp.co.sharp.android.parents.kidsguard.common.DelDeviceConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.PageSerialNumConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestCodeConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestMethodConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.thread.BusinessThread;

import static jp.co.sharp.android.parents.kidsguard.contants.Constants.SEND_KID_EXIT;

public class OkaeriNotificationActivity extends AppCompatActivity {

    public ParentBleTransfer mParentBleTransfer;
    private DealWithWaitingDlg mDealWithWaitingDlg;
    private DelDeviceConfirmDlg mDelDeviceConfirmDlg;
    private KidInfoEntity mKidInfoEntity;
    private App mApp;
    private boolean mScreenOperate = false;

    private JSONObject mOldJsonObj;
    private JSONObject mJsonObj;

    private String macAddress;
    private boolean mLockFlag = false;
    private int mViewProcess = 0;

    private Button mSubmitBtn;
    private Switch mState;



    private boolean mUnReceiver = true;
    private static final String TAG = "TAG";
    // ページジャンプ
    private boolean mPageJumpFlag = false;
    // システムホームプレス
    private boolean mSystemHomeFlag = false;

    private final static int SUCCESS_CODE = 200;
    private final static int OKAERI_SETTING_REQUEST_CODE = 1;
    private final static int PERIOD_SETTING_REQUEST_CODE = 2;
    private final static int NOTIFICATION_CONTACT_REQUEST_CODE = 3;
    // プログラムロック
    private String mSyncLock = "syncLock";
    // 編集を再開しています...
    private boolean mEditReopening = false;
    private static final int PAGE_EDIT_REOPEN = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "OkaeriNotificationActivity_onCreate");
        setContentView(R.layout.activity_okaeri_notification);

        mApp = (App) getApplication();
        initReceiver();
        initDate();

        // 検索中...
        String pDlgMsg = "キッズケータイから情報を取得しています...";
        mDealWithWaitingDlg = new DealWithWaitingDlg(OkaeriNotificationActivity.this, R.style.commonDlg, pDlgMsg, true);
        mDealWithWaitingDlg.show();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "PowerSettingActivity_onRestart");
        synchronized (mSyncLock) {
            if (mSystemHomeFlag) {
                if (mApp.getAppStatus() != Constants.APP_STATUS_USER_PRESENT) {
                    Message msg = new Message();
                    msg.what = PAGE_EDIT_REOPEN;
                    handler.sendMessage(msg);
                }
                mSystemHomeFlag = false;
            }
        }

    }


    @Override
    protected void onStop() {
        Log.i(TAG, "OkaeriNotificationActivity_onStop");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        Log.i(TAG, "OkaeriNotificationActivity_onDestroy");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "OkaeriNotificationActivity_onActivityResult");
        initReceiver();
        if (resultCode == SUCCESS_CODE) {
            try {
                switch (requestCode) {
                    case OKAERI_SETTING_REQUEST_CODE:
                        String deviceList = data.getStringExtra("deviceList");
                        formatListStrToJSONObject(deviceList, "deviceList");
                        break;
                    case PERIOD_SETTING_REQUEST_CODE:
                        if(null != data.getStringExtra("notifyList")){
                            String notifyList = data.getStringExtra("notifyList");
                            formatListStrToJSONObject(notifyList, "notifyList");
                        }
                        if(null != data.getStringExtra("deleteList")){
                            String deleteList = data.getStringExtra("deleteList");
                            formatListStrToJSONObject(deleteList, "deleteList");
                        }
                        break;
                    case NOTIFICATION_CONTACT_REQUEST_CODE:
                        String contactList = data.getStringExtra("contactList");
                        formatListStrToJSONObject(contactList, "contactList");
                        break;
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
//                e.printStackTrace();
            }
        }
    }

    public void formatListStrToJSONObject(String listStr, String name) throws Exception {
        Log.i(TAG, "OkaeriNotificationActivity_formatListStrToJSONObject");
        JSONArray array = new JSONArray(listStr);
        mJsonObj.getJSONObject("data").put(name, array);
        controlSubmitBtnChange();
    }

    /**
     * ページリターンキー、フルスクリーンリターンジェスチャー
     */
    @Override
    public void onBackPressed() {
        Log.i(TAG, "DeviceSelectorActivity_onBackPressed");
        backActivity(null);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "DeviceSelectorActivity_onStart");
        mApp.setAppStatus(Constants.APP_STATUS_INIT);
    }

    /*
     * initReceiver
     */
    public void initReceiver() {
        Log.i(TAG, "OkaeriNotificationActivity_initReceiver");

        mKidInfoEntity = ((App) getApplication()).findKidInfoBySelect();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        // ホームボタン
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED);
        registerReceiver(receiver, filter);
        registerReceiver(systemReceiver, filter);
        this.mParentBleTransfer = ((App) getApplication()).getmParentBleTransfer();
        mUnReceiver = false;
    }

    /*
     *initDate
     */
    public void initDate() {
        Log.i(TAG, "OkaeriNotificationActivity_initDate");
        macAddress = ((App) getApplication()).findKidInfoBySelect().getMacAddress();

        TextView equipmentSetting = findViewById(R.id.equipment_setting);
        equipmentSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(OkaeriNotificationActivity.this, OkaeriSettingActivity.class);
                intent.putExtra("jsonObject",mJsonObj.toString());
                startActivityForResult(intent, OKAERI_SETTING_REQUEST_CODE);
            }
        });

        LinearLayout linearLayout = findViewById(R.id.notify);
        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(OkaeriNotificationActivity.this, PeriodSettingActivity.class);
                intent.putExtra("jsonObject",mJsonObj.toString());
                startActivityForResult(intent, PERIOD_SETTING_REQUEST_CODE);
            }
        });

        TextView contacts = findViewById(R.id.contacts);
        contacts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(OkaeriNotificationActivity.this, NotificationContactActivity.class);
                intent.putExtra("jsonObject",mJsonObj.toString());
                startActivityForResult(intent, NOTIFICATION_CONTACT_REQUEST_CODE);
            }
        });

        mSubmitBtn = findViewById(R.id.submit);
        mSubmitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Dlg
                String message = "キッズケータイへ反映中..";
                mDealWithWaitingDlg = new DealWithWaitingDlg(OkaeriNotificationActivity.this, R.style.commonDlg, message, true);
                mDealWithWaitingDlg.show();
                new BusinessThread(Constants.SEND_KID_SET_INFO, mParentBleTransfer, mKidInfoEntity, submitData(), PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION).start();
            }
        });
        mState = findViewById(R.id.state);
        mState.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int data = isChecked ? 0 : 1;
                try {
                    mJsonObj.getJSONObject("data").put("state", data);
                    controlSubmitBtnChange();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        new BusinessThread(Constants.SEND_KID_IS_USING, mParentBleTransfer, mKidInfoEntity).start();
    }

    public void backActivity(View view) {
        Log.i(TAG, "OkaeriNotificationActivity_backActivity");
        try {
            if (!mJsonObj.getJSONObject("data").toString().equals(mOldJsonObj.getJSONObject("data").toString())) {
                String message = "編集内容は保存されていません。編集内容を破棄して前の画面に戻りますか？";
                mDelDeviceConfirmDlg = new DelDeviceConfirmDlg(OkaeriNotificationActivity.this, R.style.commonDlg, message);
                mDelDeviceConfirmDlg.show();
                mDelDeviceConfirmDlg.setOnOperateSetListener(new DelDeviceConfirmDlg.OnOperateSetListener() {
                    @Override
                    public void onOperateSet() {
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT, PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION, mParentBleTransfer, mKidInfoEntity).start();
                        mPageJumpFlag = true;
                    }
                });
            } else {
                mViewProcess = SEND_KID_EXIT;
                new BusinessThread(Constants.SEND_KID_EXIT, PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION, mParentBleTransfer, mKidInfoEntity).start();
                mPageJumpFlag = true;
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }

    }

    public JSONObject getInitData() {
        Log.i(TAG, "OkaeriNotificationActivity_getInitData");
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("method", RequestMethodConstants.METHOD_GET_RETURN_SETTINGS);
            jsonObject.put("data", JSONObject.NULL);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
//            e.printStackTrace();
        }
        return jsonObject;
    }

    public JSONObject submitData() {
        Log.i(TAG, "OkaeriNotificationActivity_submitData");
        JSONObject jsonObj = new JSONObject();
        try {
            Switch state = findViewById(R.id.state);
            mJsonObj.getJSONObject("data").put("state", state.isChecked() ? 0 : 1);

            jsonObj.put("method", RequestMethodConstants.METHOD_SET_RETURN_SETTINGS);
            jsonObj.put("data", mJsonObj.getJSONObject("data"));
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
//            e.printStackTrace();
        }
        return jsonObj;
    }

    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_SCREEN_OFF);
                        mScreenOperate = true;
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT, PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION, mParentBleTransfer, mKidInfoEntity).start();
                    }
                } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                        if (!mPageJumpFlag) {
                            Message msg = new Message();
                            msg.what = PAGE_EDIT_REOPEN;
                            handler.sendMessage(msg);
                        }
                    }
                } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_SCREEN_OFF);
                        mSystemHomeFlag = true;
                        mScreenOperate = true;
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT,
                                mParentBleTransfer,
                                mKidInfoEntity,
                                null,
                                PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION).start();
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    // 初期化
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String macAddress = bluetoothReceiverDto.getAddress();
                    if (mApp.isMimamoriCheck(macAddress)) {
                        mApp.addmLsIsMimamori(macAddress);

                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT,
                                mParentBleTransfer,
                                mKidInfoEntity,
                                null,
                                PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION).start();
                        // ページジャンプ
                        mPageJumpFlag = true;
                        Intent intent1 = new Intent();
                        intent1.setAction(Constants.ACTION_IS_MIMAMORI);
                        intent1.setClass(OkaeriNotificationActivity.this, HomeActivity.class);
                        startActivity(intent1);
                    } else {
                        mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                        mApp.updateKidInfo(mKidInfoEntity);

                        String message = mKidInfoEntity.getKidName() + "と切断されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(OkaeriNotificationActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                processWarringDlg.dismiss();
                                // ページジャンプ
                                mPageJumpFlag = true;
                                Intent intent1 = new Intent();
                                intent1.setClass(OkaeriNotificationActivity.this, SettingActivity.class);
                                startActivity(intent1);
                            }
                        });
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };


    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "OkaeriNotificationActivity_BroadcastReceiver");
            try {
                String action = intent.getAction();
                if (RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    if (bluetoothReceiverDto.isFinished()) {
                        switch (mViewProcess) {
                            case Constants.SEND_KID_ENTER:
                                mViewProcess = Constants.SEND_KID_GET_INFO;
                                if (!mScreenOperate) {
                                    new BusinessThread(Constants.SEND_KID_GET_INFO, mParentBleTransfer, mKidInfoEntity, getInitData(), PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION).start();
                                } else {
                                    mEditReopening = false;
                                    mScreenOperate = false;
                                    handler.sendEmptyMessage(0);
                                }
                                break;
                            case Constants.SEND_KID_EXIT:
                                if (mDelDeviceConfirmDlg != null && mDelDeviceConfirmDlg.isShowing()) {
                                    mDelDeviceConfirmDlg.dismiss();
                                }
                                if (!mScreenOperate) {
                                    // ページジャンプ
                                    mPageJumpFlag = true;
                                    Intent intent1 = new Intent();
                                    intent1.setClass(OkaeriNotificationActivity.this, SettingActivity.class);
                                    startActivity(intent1);
                                }

                                break;
                        }
                    }
                } else if ( RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String retStr = bluetoothReceiverDto.getRetStr();
                    JSONObject jsonObject = new JSONObject(retStr);
                    if (mLockFlag && RequestMethodConstants.METHOD_GET_RETURN_SETTINGS.equals(jsonObject.getString("method"))) {
                        mJsonObj = new JSONObject(jsonObject.toString());
                        mOldJsonObj = new JSONObject(retStr);

                        mDealWithWaitingDlg.dismiss();
                        //getUser
                        TextView textView = findViewById(R.id.userName);
                        textView.setText((mApp.findKidInfoBySelect().getKidName() + "のキッズケータイ"));
                        //set State
                        setSwitchState(jsonObject);
                        //
                    } else if (RequestMethodConstants.METHOD_GET_OPERATING_STATE.equals(jsonObject.getString("method"))) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        if (Constants.IS_USING_OK.equals(data.getString("state"))) {
                            //send enter
                            mLockFlag = true;
                            mViewProcess = Constants.SEND_KID_ENTER;
                            new BusinessThread(Constants.SEND_KID_ENTER, PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION, mParentBleTransfer, mKidInfoEntity).start();
                        } else {
                            mDealWithWaitingDlg.dismiss();
                            String message = "別のスマートフォンから操作中のため、設定を変更できません。";
                            ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(OkaeriNotificationActivity.this, R.style.commonDlg, message);
                            processWarringDlg.show();
                            processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                @Override
                                public void onOperateSet() {
                                    processWarringDlg.dismiss();
                                    mPageJumpFlag=true;
                                    OkaeriNotificationActivity.this.finish();
                                }
                            });
                        }
                    } else if (RequestMethodConstants.METHOD_ON_SYNC_RESULT.equals(jsonObject.getString("method"))) {
                        if (Constants.ON_SYNC_RESULT.equals(jsonObject.getString("result"))) {
                            mDealWithWaitingDlg.dismiss();
                            // ページジャンプ
                            mPageJumpFlag = true;
                            mViewProcess = Constants.SEND_KID_EXIT;
                            new BusinessThread(Constants.SEND_KID_EXIT, PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION, mParentBleTransfer, mKidInfoEntity).start();
//                            Intent intent1 = new Intent();
//                            intent1.setClass(OkaeriNotificationActivity.this, SettingActivity.class);
//                            startActivity(intent1);

                        }else {
                            handler.sendEmptyMessage(0);
                            String message = "キッズケータイへ反映できませんでした";
                            ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(OkaeriNotificationActivity.this, R.style.commonDlg, message);
                            processWarringDlg.show();
                            processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                @Override
                                public void onOperateSet() {
                                    processWarringDlg.dismiss();
                                }
                            });
                        }
                    } else if (RequestMethodConstants.METHOD_ON_OPERATE_INTERRUPT.equals(jsonObject.getString("method"))) {
                        String message = "キッズケータイが操作されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(OkaeriNotificationActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                mPageJumpFlag=true;
                                Intent intent1 = new Intent(OkaeriNotificationActivity.this,SettingActivity.class);
                                startActivity(intent1);
                                processWarringDlg.dismiss();
                            }
                        });
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
//                e.printStackTrace();
            }
        }
    };


    public void controlSubmitBtnChange() throws JSONException {
        Log.i(TAG, "OkaeriNotificationActivity_controlSubmitBtnChange");
        if (mJsonObj.getJSONObject("data").toString().equals(mOldJsonObj.getJSONObject("data").toString())) {
            mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
            mSubmitBtn.setClickable(false);
        } else {
            mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
            mSubmitBtn.setClickable(true);
        }
    }

    public void setSwitchState(JSONObject jsonObject) throws Exception {
        int state = jsonObject.getJSONObject("data").getInt("state");
        Switch sw = findViewById(R.id.state);
        if (state == 0) {
            sw.setChecked(true);
        } else {
            sw.setChecked(false);
        }
    }

    /**
     * Dialog閉じる
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                mDealWithWaitingDlg.dismiss();
            } else if (msg.what == PAGE_EDIT_REOPEN) {
                if (!mEditReopening) {
                    String message = "編集を再開しています...";
                    mDealWithWaitingDlg = new DealWithWaitingDlg(OkaeriNotificationActivity.this, R.style.commonDlg, message, false);
                    mDealWithWaitingDlg.show();
                    mScreenOperate = true;
                    mViewProcess = Constants.SEND_KID_IS_USING;
                    new BusinessThread(Constants.SEND_KID_IS_USING,
                            mParentBleTransfer,
                            mKidInfoEntity,
                            null,
                            PageSerialNumConstants.PAGE_SERIAL_NUM_POWER_SETTING).start();
                    // ブロードキャストの再登録
                    unregisterReceiver(systemReceiver);
                    initReceiver();
                    mEditReopening = true;
                }
            }
        }
    };

}
